class UsersController < ApplicationController
  before_filter :check_admin_right,:only=>[:index,:destroy,:list_role,:update_role]
  before_filter :login_required,:only => [:generate_recommend_code]
  before_filter :find_user,:only => [:generate_recommend_code]
  # Be sure to include AuthenticationSystem in Application Controller instead
  
  def index
    @users = User.paginate :page => params[:page],:per_page =>20
  end

  # render new.rhtml
  def new
    @user = User.new()
  end

  def create
    #    if simple_captcha_valid?
    cookies.delete :auth_token
    # protects against session fixation attacks, wreaks havoc with
    # request forgery protection.
    # uncomment at your own risk
    # reset_session
    @user = User.recommend_new(params[:user],params[:rc])
    if @user.errors.empty?
      self.current_user = @user
      redirect_back_or_default('/')
      flash[:notice] = "Welcome"
    else
      render :action => 'new'
    end
    #    else
    #      flash[:notice] = "验证码错误!"
    #      render :action => 'new'
    #    end
  end
  
  # render edit.rhtml
  def edit
    @user = User.find(params[:id])
  end

  def change_password
    @user = User.find(params[:id])
  end

  def update_password
    @user = User.find(current_user)
    if User.authenticate(@user.login, params[:old_password])
      if @user.update_attributes(params[:user])
        flash[:notice] = "密码修改成功"
        redirect_to '/store/mine'
      else
        render :action => 'edit'
      end
    else
      flash[:notice] = "旧密码不正确"
      render :action => 'edit'
    end
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      flash[:notice] = "用户资料修改成功"
      redirect_to '/store/mine'
    else
      render :action => 'edit'
    end
  end

  def destroy
    @user = User.find(params[:id])
    @user.destroy

    respond_to do |format|
      format.html { redirect_to(users_url) }
      format.xml  { head :ok }
    end
  end

  def check_login
    result = User.find_by_login(params[:user][:login]) ? "false":"true"
    render :text=>   result
  end

  def check_email
    result = User.find_by_email(params[:user][:email]) ? "false":"true"
    render :text=>   result.to_s
  end

  def check_rc
    result = RecommendCode.find_by_code(params[:rc]) ? "true":"false"
    render :text=>   result.to_s
  end

  def list_role
    @user=User.find(params[:id])
    @all_roles = Role.find(:all)
  end

  def update_role
    @user=User.find(params[:id])
    @user.roles.clear

    for item_hash in params[:role].values
      #chech_box没有选中的时候，提交的值为"0"
      if item_hash.values[0] !="0"
        role=Role.find(item_hash.values[0])
        @user.roles << role
      end
    end

    if @user.save
      flash[:notice] = '修改成功'
      redirect_to :action=>'index'
    end
  end

  def generate_recommend_code
    @rc = User.generate_recommend_code(@user.id)
  end

end
